package com.xszx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取url
        String url = req.getRequestURL().toString();
        if (url.contains("login.jsp") || url.contains("/ManagerLoginServlet") || url.contains("/LoginServlet")) {
            //登录界面
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (url.contains("admin")) {
            String managerName = req.getSession().getAttribute("managerName").toString();
            if (managerName == null) {
                resp.getWriter().write("请登录");
                return;
            }
        }else if (url.contains("user")) {
            String username = req.getSession().getAttribute("username").toString();
            if (username == null) {
                resp.getWriter().write("请登录");
                return;
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
